<template>
	<view class="detail-container">
		<!-- Tab切换区域 -->
		<view class="tab-container">
			<view class="tab-box">
				<view 
					v-for="(tab, index) in tabs" 
					:key="index"
					class="tab-item"
					:class="{ active: currentTab === index }"
					@tap="switchTab(index)"
				>
					<text>{{ tab }}</text>
				</view>
			</view>
		</view>

		<!-- 内容区域 -->
		<scroll-view scroll-y class="scroll-view">
			<!-- 详情 -->
			<view v-if="currentTab === 0" class="info-section">
				<view class="info-row">
					<text class="info-label">名称</text>
					<text class="info-value">{{ deviceInfo.name || '-' }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">设备配置</text>
					<text class="info-value">{{ deviceInfo.deviceProfileName || '-' }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">标签</text>
					<text class="info-value">{{ deviceInfo.label || '-' }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">状态</text>
					<text class="info-value" :class="{ 'active-status': deviceInfo.active }">
						{{ deviceInfo.active ? '在线' : '离线' }}
					</text>
				</view>
				<view class="info-row">
					<text class="info-label">客户</text>
					<text class="info-value">{{ deviceInfo.customerTitle || '-' }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">是否网关</text>
					<text class="info-value">{{ deviceInfo.additionalInfo?.gateway ? '网关' : '设备' }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">说明</text>
					<text class="info-value">{{ deviceInfo.additionalInfo?.description || '-' }}</text>
				</view>
			</view>

			<!-- 属性 -->
			<view v-if="currentTab === 1" class="attribute-container">
				<!-- 属性范围选择 -->
				<view class="scope-picker">
					<picker @change="handleScopeChange" :value="scopeIndex" :range="scopeOptions" range-key="label">
						<view class="picker-content">
							<text class="picker-text">{{ scopeOptions[scopeIndex].label }}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>

				<!-- 属性列表 -->
				<view class="card-list">
					<view class="card-item" v-for="(attr, index) in attributes" :key="index">
						<view class="card-header">
							<text class="update-time">最后更新时间：{{ formatTime(attr.lastUpdateTs) }}</text>
						</view>
						<view class="card-content">
							<view class="content-row">
								<text class="content-label">键名：</text>
								<text class="content-value">{{ attr.key }}</text>
							</view>
							<view class="content-row">
								<text class="content-label">数值：</text>
								<text class="content-value">{{ attr.value }}</text>
							</view>
						</view>
					</view>
					<view v-if="attributes.length === 0" class="no-data">
						<text>暂无属性数据</text>
					</view>
				</view>
			</view>

			<!-- 遥测 -->
			<view v-if="currentTab === 2" class="telemetry-container">
				<!-- 遥测列表 -->
				<view class="card-list">
					<view class="card-item" v-for="(item, index) in telemetry" :key="index">
						<view class="card-header">
							<text class="update-time">最后更新时间：{{ formatTime(item.lastUpdateTs) }}</text>
						</view>
						<view class="card-content">
							<view class="content-row">
								<text class="content-label">键名：</text>
								<text class="content-value">{{ item.key }}</text>
							</view>
							<view class="content-row">
								<text class="content-label">数值：</text>
								<text class="content-value">{{ item.value }}</text>
							</view>
						</view>
					</view>
					<view v-if="telemetry.length === 0" class="no-data">
						<text>暂无遥测数据</text>
					</view>
				</view>
			</view>

			<!-- 告警 -->
			<view v-if="currentTab === 3" class="alarm-container">
				<!-- 告警状态选择 -->
				<view class="status-picker">
					<picker @change="handleStatusChange" :value="statusIndex" :range="statusOptions" range-key="label">
						<view class="picker-content">
							<text class="picker-text">{{ statusOptions[statusIndex].label }}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>

				<!-- 告警列表 -->
				<view class="card-list">
					<view class="alarm-item" 
						:class="alarm.severity.toLowerCase()" 
						v-for="(alarm, index) in alarms" 
						:key="index"
					>
						<view class="alarm-content">
							<!-- 第一行：类型和时间 -->
							<view class="alarm-row">
								<text class="alarm-type">{{ alarm.type }}</text>
								<text class="alarm-time">{{ formatTime(alarm.createdTime) }}</text>
							</view>
							
							<!-- 第二行：发起者和严重程度 -->
							<view class="alarm-row">
								<text class="alarm-originator">{{ alarm.originatorName || '-' }}</text>
								<view class="severity-tag" :class="alarm.severity.toLowerCase()">
									{{ severityMap[alarm.severity] || alarm.severity }}
								</view>
							</view>
							
							<!-- 第三行：状态 -->
							<view class="alarm-row">
								<view class="status-tag" :class="alarm.status.toLowerCase()">
									{{ statusMap[alarm.status] || alarm.status }}
								</view>
							</view>
							
							<!-- 分割线 -->
							<view class="divider"></view>
							
							<!-- 操作按钮 -->
							<view class="alarm-actions">
								<view class="action-btn ack-btn" 
									v-if="alarm.status === 'ACTIVE_UNACK'"
									@tap="handleAck(alarm)"
								>应答</view>
								<view class="action-btn clear-btn" 
									v-if="alarm.status === 'ACTIVE_ACK' || alarm.status === 'ACTIVE_UNACK'"
									@tap="handleClear(alarm)"
								>清除</view>
							</view>
						</view>
					</view>
					<view v-if="alarms.length === 0" class="no-data">
						<text>暂无告警数据</text>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import request from '@/utils/request.js'
import { formatTime } from '@/utils/timeUtils.js'
export default {
	data() {
		return {
			tabs: ['详情', '属性', '遥测', '告警'],
			currentTab: 0,
			deviceId: '',
			deviceInfo: {},
			attributes: [],
			telemetry: [],
			scopeOptions: [
				{ label: '客户端属性', value: 'CLIENT_SCOPE' },
				{ label: '服务端属性', value: 'SERVER_SCOPE' },
				{ label: '共享属性', value: 'SHARED_SCOPE' }
			],
			scopeIndex: 1,
			statusOptions: [
				{ label: '激活', value: 'ACTIVE' },
				{ label: '已清除', value: 'CLEARED' },
				{ label: '已确认', value: 'ACK' },
				{ label: '已清除已确认', value: 'UNACK' }
			],
			statusIndex: 0,
			alarms: [],
			// 添加告警严重程度映射
			severityMap: {
				'CRITICAL': '严重',
				'MAJOR': '重要',
				'MINOR': '次要',
				'WARNING': '警告',
				'INDETERMINATE': '未定'
			},
			// 添加状态映射
			statusMap: {
				'ACTIVE_ACK': '激活已确认',
				'ACTIVE_UNACK': '激活未确认',
				'CLEARED_ACK': '清除已确认',
				'CLEARED_UNACK': '清除未确认'
			}
		}
	},

	onLoad(options) {
		this.deviceId = options.deviceId
		this.loadTabData(0)
	},

	methods: {
		// 移除本地的 formatTime 方法，改用导入的方法
		formatTime,
		
		// 切换tab
		switchTab(index) {
			this.currentTab = index
			this.loadTabData(index)
		},

		// 加载数据
		async loadTabData(index) {
			switch(index) {
				case 0:
					await this.loadDeviceInfo()
					break
				case 1:
					await this.loadAttributes()
					break
				case 2:
					await this.loadTelemetry()
					break
				case 3:
					await this.loadAlarms()
					break
			}
		},

		// 加载设备详情
		async loadDeviceInfo() {
			try {
				const result = await request.get(`/api/device/info/${this.deviceId}`)
				if (result) {
					this.deviceInfo = result
					// 设置导航栏标题为设备名称
					uni.setNavigationBarTitle({
						title: result.name || '设备详情'
					})
				}
			} catch (error) {
				console.error('获取设备详情失败:', error)
				uni.showToast({
					title: '获取设备详情失败',
					icon: 'none'
				})
			}
		},

		// 加载属性
		async loadAttributes() {
			try {
				const scope = this.scopeOptions[this.scopeIndex].value
				const result = await request.get(
					`/api/plugins/telemetry/DEVICE/${this.deviceId}/values/attributes/${scope}`
				)
				if (result) {
					this.attributes = result
				}
			} catch (error) {
				console.error('获取属性失败:', error)
				uni.showToast({
					title: '获取属性失败',
					icon: 'none'
				})
			}
		},

		// 加载遥测
		async loadTelemetry() {
			try {
				const result = await request.get(
					`/api/plugins/telemetry/DEVICE/${this.deviceId}/values/timeseries?useStrictDataTypes=false`
				)
				if (result) {
					// 将对象转换为数组格式
					this.telemetry = Object.entries(result).map(([key, value]) => ({
						key,
						value: value[0].value,
						lastUpdateTs: value[0].ts
					}))
				}
			} catch (error) {
				console.error('获取遥测失败:', error)
				uni.showToast({
					title: '获取遥测失败',
					icon: 'none'
				})
			}
		},

		// 加载告警
		async loadAlarms() {
			try {
				const status = this.statusOptions[this.statusIndex].value
				const result = await request.get(
					`/api/v2/alarm/DEVICE/${this.deviceId}?statusList=${status}&pageSize=100&page=0`
				)
				if (result?.data) {
					this.alarms = result.data
				}
			} catch (error) {
				console.error('获取告警失败:', error)
				uni.showToast({
					title: '获取告警失败',
					icon: 'none'
				})
			}
		},

		// 格式化标签
		formatTags(tags) {
			if (!tags) return ''
			return Object.entries(tags)
				.map(([key, value]) => `${key}: ${value}`)
				.join(', ')
		},

		// 处理属性范围选择
		handleScopeChange(e) {
			this.scopeIndex = e.detail.value
			this.loadAttributes()
		},

		// 处理告警状态选择
		handleStatusChange(e) {
			this.statusIndex = e.detail.value
			this.loadAlarms()
		},

		// 处理应答
		async handleAck(alarm) {
			try {
				await request.post(`/api/alarm/${alarm.id.id}/ack`)
				// 刷新告警列表
				this.loadAlarms()
				uni.showToast({
					title: '应答成功',
					icon: 'success'
				})
			} catch (error) {
				console.error('应答失败:', error)
				uni.showToast({
					title: '应答失败',
					icon: 'none'
				})
			}
		},

		// 处理清除
		async handleClear(alarm) {
			try {
				await request.post(`/api/alarm/${alarm.id.id}/clear`)
				// 刷新告警列表
				this.loadAlarms()
				uni.showToast({
					title: '清除成功',
					icon: 'success'
				})
			} catch (error) {
				console.error('清除失败:', error)
				uni.showToast({
					title: '清除失败',
					icon: 'none'
				})
			}
		}
	}
}
</script>

<style>
.detail-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	display: flex;
	flex-direction: column;
}

.tab-container {
	background-color: #fff;
	height: 88rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 30rpx;
}

.tab-box {
	background-color: #F5F5F5;
	border-radius: 32rpx;
	display: flex;
	padding: 4rpx;
	width: 100%;
}

.tab-item {
	flex: 1;
	height: 56rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #666;
	border-radius: 28rpx;
	transition: all 0.3s;
}

.tab-item.active {
	background-color: #305680;
	color: #fff;
	font-weight: 500;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.scroll-view {
	flex: 1;
	height: calc(100vh - 88rpx);
	background-color: #f5f5f5;
}

/* 详情样式 */
.info-section {
	margin: 20rpx;
	padding: 0 30rpx;
	background-color: #fff;
	border-radius: 12rpx;
}

.info-row {
	display: flex;
	padding: 24rpx 0;
	border-bottom: 1rpx solid #eee;
	justify-content: space-between;
	align-items: center;
}

.info-row:last-child {
	border-bottom: none;
}

.info-label {
	width: 160rpx;
	color: #666;
	font-size: 28rpx;
	flex-shrink: 0;
}

.info-value {
	color: #333;
	font-size: 28rpx;
	text-align: right;
	flex: 1;
}

.active-status {
	color: #058C05;
}

/* 属性和遥测卡片样式 */
.card-list {
	padding: 20rpx;
}

.card-item {
	background-color: #fff;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
}

.card-header {
	padding: 20rpx;
	border-bottom: 1rpx solid #eee;
}

.update-time {
	font-size: 24rpx;
	color: #999;
}

.card-content {
	padding: 20rpx;
}

.content-row {
	display: flex;
	margin-bottom: 16rpx;
}

.content-row:last-child {
	margin-bottom: 0;
}

.content-label {
	width: 120rpx;
	color: #666;
	font-size: 28rpx;
}

.content-value {
	flex: 1;
	color: #333;
	font-size: 28rpx;
}

.developing {
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #999;
	font-size: 28rpx;
}

.no-data {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 200rpx;
	color: #999;
	font-size: 28rpx;
}

/* 属性范围选择器样式 */
.attribute-container {
	display: flex;
	flex-direction: column;
	height: 100%;
}

.scope-picker {
	background-color: #fff;
	padding: 20rpx;
	margin: 20rpx;
	border-radius: 12rpx;
}

.picker-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
	height: 60rpx;
}

.picker-text {
	font-size: 28rpx;
	color: #333;
}

.picker-arrow {
	font-size: 24rpx;
	color: #999;
}

/* 遥测容器样式 */
.telemetry-container {
	display: flex;
	flex-direction: column;
	height: 100%;
	padding-top: 20rpx;  /* 添加顶部间距 */
}

/* 修改卡片列表样式 */
.card-list {
	flex: 1;
	padding: 0 20rpx;
}

/* 卡片样式 */
.card-item {
	background-color: #fff;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
}

/* 告警容器样式 */
.alarm-container {
	display: flex;
	flex-direction: column;
	height: 100%;
}

.status-picker {
	background-color: #fff;
	padding: 20rpx;
	margin: 20rpx;
	border-radius: 12rpx;
}

/* 修改卡片列表样式 */
.card-list {
	flex: 1;
	padding: 0 20rpx;
}

.alarm-item {
	background: #FFFFFF;
	border-radius: 8px;
	margin: 8px 0;
	padding: 12px 16px;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	border-left: 5px solid transparent;
	
	&.critical {
		border-left-color: #FF4D4F;
	}
	
	&.major {
		border-left-color: #FF7A45;
	}
	
	&.minor {
		border-left-color: #FFA940;
	}
	
	&.warning {
		border-left-color: #FAAD14;
	}
}

.alarm-content {
	.alarm-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 8px;
		
		.alarm-type {
			font-size: 18px;
			color: #333;
			font-weight: 600;
		}
		
		.alarm-time {
			font-size: 14px;
			color: #999;
		}
		
		.alarm-originator {
			font-size: 14px;
			color: #666;
		}
		
		.severity-tag {
			padding: 4px 12px;
			border-radius: 4px;
			font-size: 14px;
			
			&.critical {
				color: #fff;
				background-color: #FF4D4F;
			}
			
			&.major {
				color: #fff;
				background-color: #FF7A45;
			}
			
			&.minor {
				color: #fff;
				background-color: #FFA940;
			}
			
			&.warning {
				color: #fff;
				background-color: #FAAD14;
			}
		}
		
		.status-tag {
			padding: 4px 12px;
			border-radius: 4px;
			font-size: 14px;
			color: #305680;
			background-color: rgba(48, 86, 128, 0.1);
		}
	}
	
	.divider {
		height: 1px;
		background-color: #EEEEEE;
		margin: 8px -16px;
		padding: 0 16px;
	}
	
	.alarm-actions {
		display: flex;
		justify-content: flex-end;
		gap: 12px;
		margin-top: 8px;
		
		.action-btn {
			padding: 4px 16px;
			border-radius: 4px;
			font-size: 14px;
			color: #fff;
			background-color: #305680;
			
			&.ack-btn {
				background-color: #305680;
			}
			
			&.clear-btn {
				background-color: #305680;
			}
		}
	}
}
</style>
